package com.yang.chatMessage.controller;

import jakarta.annotation.Resource;
import org.springframework.ai.chat.ChatResponse;
import org.springframework.ai.chat.prompt.Prompt;
import org.springframework.ai.openai.OpenAiChatClient;
import org.springframework.ai.openai.OpenAiChatOptions;
import org.springframework.ai.openai.api.OpenAiApi;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import reactor.core.publisher.Flux;

@RestController
public class ChatController {
    @Resource
    private OpenAiChatClient openAiChatClient;

    @RequestMapping("/ai/chat")
    public String chat(@RequestParam(value = "msg") String msg){
        return openAiChatClient.call(msg);

    }

    @RequestMapping("/ai/chat2")
    public String chatCall(@RequestParam(value = "msg") String msg){
        ChatResponse response = openAiChatClient.call(new Prompt(msg));
        return response.getResult().getOutput().getContent();

    }

    @RequestMapping("/ai/chat4")
    public String chatCall2(@RequestParam(value = "msg") String msg){
        //可选参数可以覆盖 项目配置文件中的参数(以代码中内容为准)
        ChatResponse response = openAiChatClient.call(
                new Prompt(
                        msg,
                        OpenAiChatOptions.builder()
                                .withModel("gpt-4-vision-preview") //gpt版本 可以填写字符串或者使用OpenAiApi.ChatModel中提供的常量
                                .withTemperature(0.8F) //温度高，回答创新型越高；越低，越准确
                                .build()
                )
        );
        return response.getResult().getOutput().getContent();

    }

    @RequestMapping("/ai/chat5")
    public Object chatStream(@RequestParam(value = "msg") String msg){
        Flux<ChatResponse> flux = openAiChatClient.stream(new Prompt(msg,
                        OpenAiChatOptions.builder()
                                .withModel(OpenAiApi.ChatModel.GPT_4_VISION_PREVIEW.getValue()) //gpt版本 "gpt-4-vision-preview"
                                .withTemperature(0.5F) //温度高，回答创新型越高；越低，越准确
                                .withMaxTokens(4096) //显示最大token
                                .build()
                )
        );
        flux.toStream().forEach(chatResponse -> {
            System.out.print(chatResponse.getResult().getOutput().getContent());
        });
        return flux.collectList();
    }


}
